package cn.starlightsoftware.sherly.framework.mybatisplus.handler;

import cn.hutool.core.collection.CollUtil;
import cn.starlightsoftware.sherly.framework.tenant.config.TenantConfig;
import cn.starlightsoftware.sherly.framework.tenant.config.TenantContextHolder;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 谷子毅
 */
@Component
public class TenantHandler implements TenantLineHandler {

    private final Set<String> ignoreTables = new HashSet<>();

    public TenantHandler(TenantConfig config) {
        // 不同 DB 下，大小写的习惯不同，所以需要都添加进去
        config.getIgnoreTables().forEach(table -> {
            ignoreTables.add(table.toLowerCase());
            ignoreTables.add(table.toUpperCase());
        });
    }

    @Override
    public Expression getTenantId() {
        return new StringValue(TenantContextHolder.getRequiredTenantId());
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return TenantContextHolder.isIgnore() // 情况一，全局忽略多租户
            || CollUtil.contains(ignoreTables, tableName); // 情况二，忽略多租户的表
    }
}
